package com.kt.emall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kt.common.utils.HttpUtils;
import com.kt.emall.member.dao.MemberLevelDao;
import com.kt.emall.member.entity.MemberLevelEntity;
import com.kt.emall.member.exception.PhoneExistException;
import com.kt.emall.member.exception.UsernameExistException;
import com.kt.emall.member.vo.MemberLoginVO;
import com.kt.emall.member.vo.MemberRegVO;
import com.kt.emall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kt.common.utils.PageUtils;
import com.kt.common.utils.Query;

import com.kt.emall.member.dao.MemberDao;
import com.kt.emall.member.entity.MemberEntity;
import com.kt.emall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegVO memberRegVO) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        // 检查用户名和手机号是否唯一，为了让controller感知异常 => 异常机制
        checkPhoneUnique(memberRegVO.getPhone());
        checkUsernameUnique(memberRegVO.getUsername());

        entity.setMobile(memberRegVO.getPhone());
        entity.setUsername(memberRegVO.getUsername());
        entity.setNickname(memberRegVO.getUsername());

        // 加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegVO.getPassword());
        entity.setPassword(encode);

        // 其他信息...

        // 保存
        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobileCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobileCount > 0) {
            throw new PhoneExistException();
        }
    }


    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer usernameCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (usernameCount > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVO memberLoginVO) {
        String account = memberLoginVO.getUserAccount();
        String password = memberLoginVO.getPassword();

        // 1、去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("mobile", account).or().eq("username", account));
        if (memberEntity == null) {
            // 登录失败
            return null;
        } else {
            // 从数据库中获取的密码
            String passwordFormDB = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            // 密码匹配
            if (encoder.matches(password, passwordFormDB)) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 登录和注册合并逻辑
        String uid = socialUser.getUid();
        // 1、判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        // 使用baseMapper时，实体类中的属性名必须与数据库中的列名对应
        MemberEntity selectOne = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (selectOne != null) {
            // 这个用户已经注册
            MemberEntity entity = new MemberEntity();
            entity.setId(selectOne.getId());
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpiresIn(socialUser.getExpiresIn());

            memberDao.updateById(entity);
            selectOne.setAccessToken(selectOne.getAccessToken());
            selectOne.setExpiresIn(selectOne.getExpiresIn());
            return selectOne;
        } else {
            // 没有查到当前社交用户对应的记录，注册
            MemberEntity registerEntity = new MemberEntity();
            try {
                // 查询当前社交用户的社交账号信息
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccessToken());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String nickName = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    registerEntity.setNickname(nickName);
                    registerEntity.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            registerEntity.setSocialUid(socialUser.getUid());
            registerEntity.setAccessToken(socialUser.getAccessToken());
            registerEntity.setExpiresIn(socialUser.getExpiresIn());
            memberDao.insert(registerEntity);
            return registerEntity;
        }
    }

}
